﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

namespace project_web2.AdminTool
{
    public partial class ManagerProducts : System.Web.UI.Page
    {
        DAL dal = new DAL();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["Login"] == null) {
                Response.Redirect("Login.aspx");
            }
            grManagerProducts.AllowPaging = true;
            grManagerProducts.PageSize = 5;
            if (!IsPostBack) {
                LoadGriview();
            }    
        }

        private void LoadGriview() {
            grManagerProducts.DataSource = loadInfoProducts();
            grManagerProducts.DataBind();
        }
        private DataTable loadInfoProducts()
        {
            string sql = "select * from Products";
            return dal.get_data(sql);
        }

        protected void btnAdd_Click(object sender, EventArgs e) {
            Response.Redirect("AddandEditProduct.aspx");
        }

        protected void grManagerProducts_PageIndexChanging(object sender, GridViewPageEventArgs e) {
            grManagerProducts.EditIndex = -1;
            grManagerProducts.PageIndex = e.NewPageIndex;
            LoadGriview();
        }

        protected void grManagerProducts_RowCommand(object sender, GridViewCommandEventArgs e) {
            int index = Convert.ToInt32(e.CommandArgument.ToString());
            if (e.CommandName == "Xoa") {
                string id = grManagerProducts.DataKeys[index].Value.ToString();
                deleteRow(id);
            } else if (e.CommandName == "Sua") {
                string id = grManagerProducts.DataKeys[index].Value.ToString();
                Response.Redirect("AddandEditProduct.aspx?id="+id);
            }

            LoadGriview();
        }
        private void deleteRow(string id) {
            string sql = "delete from Products where productid =" + id;
            dal.executeQuery(sql);
        }
        protected void grManagerProducts_RowDataBound(object sender, GridViewRowEventArgs e) {
            if (e.Row.RowType == DataControlRowType.DataRow && (e.Row.RowState == DataControlRowState.Alternate || e.Row.RowState == DataControlRowState.Normal)) {
                Button bt = (Button)e.Row.Cells[9].Controls[0];
                bt.OnClientClick = "if(!confirm('Bạn thật sự muốn xóa!')) return false;";
            }
        }
    }
}